package recursion;

/**
 * 求一个数的阶乘
 * 0!=1
 * 1!=1
 * 2!=2*1=2
 * 3!=3*2*1=6
 * 4!=4*3*2*1=24
 */
public class Demo02 {
	public static void main(String[] args) {
		System.out.println(getFactorial(4));
		System.out.println(getFactorial(3));

		System.out.println(getFactorial2(4));
		System.out.println(getFactorial2(3));
	}
	public static int getFactorial(int n) {
		/**
		 * n=n*(n-1)*(n-2)*...1
		 */
		int sum = 1;
		for (int i=n; i>1 ;i--){ //第一次循环: sum = 1*4 = 4
			//累计求乘积           //第二次循环: sum = 4*3  =12
			                     //第三次循环: sum = 12*2  =24
			sum *= i;
		}
		return sum;
	}

	public static int getFactorial2(int n) {
		/**
		 * 0!=1
		 * 1!=1
		 *
		 * 2!= 2*1!
		 * 3!=3*2!
		 * 4!=4*3!
		 * ..
		 * n!=n*(n-1)!
		 */
		if (n==0 || n==1) {
			return 1;
		}
		return n * getFactorial2(n - 1);
	}
}
